<template>
  <div>
    <!-- 面包屑 -->
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品列表</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-card>
      <!-- 提示 -->
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
      <!-- 进度条 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"> </el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        label-position="top"
        label-width="80px"
        :rules="AddCateRules"
        ref="AddCateref"
        :model="AddGoodsCate"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          @tab-click="tabclicked"
          :before-leave="beforeTabLeave"
        >
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="AddGoodsCate.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="AddGoodsCate.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="AddGoodsCate.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="AddGoodsCate.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="AddGoodsCate.goods_cat"
                :options="CateList"
                expand-trigger="hover"
                :props="propCate"
                @change="AddCateChange"
              ></el-cascader>
            </el-form-item>
            <!-- <el-form-item label="商品分介绍">
          <el-input v-model="AddGoodsCate.goods_introduce"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-input v-model="AddGoodsCate.pics"></el-input>
        </el-form-item> -->
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染商品参数 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manytabledata"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals" size="small">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  border
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in OnlyTableList"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 上传图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="actionUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="HeaderObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary"
                >点击上传</el-button
              ></el-upload
            >
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="AddGoodsCate.goods_introduce"></quill-editor>
            <el-button type="primary" class="btnAdd" @click="Addshop"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片展示" :visible.sync="peiviewVisible" width="50%">
      <img :src="Previewpath" alt="" class="priviewimg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      // 添加商品名称
      AddGoodsCate: {
        goods_name: '',
        // 商品所属的分类数组
        goods_cat: [],
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 储存图片
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      CateList: [],
      propCate: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      activeIndex: '0',
      // 验证规则
      AddCateRules: {
        goods_name: [
          { required: true, message: '请输入商品名', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 动态参数列表的获取
      manytabledata: [],
      // 静态参数列表的获取
      OnlyTableList: [],
      // 图片保存地址
      actionUrl: 'https://www.liulongbin.top:8888/api/private/v1/upload',
      HeaderObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 定义图片路径
      Previewpath: '',
      // 展示图片对话框
      peiviewVisible: false
    }
  },
  created() {
    this.getGoodsCate()
  },
  methods: {
    // 下一步
    // next() {
    //   if (this.activeIndex++ > 5) this.activeIndex = 0
    // }
    async getGoodsCate() {
      const { data: res } = await this.$http.get('categories')
      // console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败')
      }
      this.CateList = res.data
      // console.log(this.goods_cat[0].cat_id)
    },
    AddCateChange() {
      console.log(this.propCate.Cat_name)
    },
    beforeTabLeave(activeName, oldActiveName) {
      // console.log('即将离开的' + oldActiveName)
      // console.log('即将进入的' + activeName)
      // // 阻止进入下一页
      // return false
      if (oldActiveName === '0' && this.AddGoodsCate.goods_cat.length !== 3) {
        // eslint-disable-next-line brace-style
        this.$message.error('请选择三级内容')
        return false
      }
    },
    async tabclicked() {
      // console.log(this.activeIndex)
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取动态参数列表失败！')
        }
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        // console.log(res.data)
        this.manytabledata = res.data
        // this.$message.success('获取动态参数列表成功！！')
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取静态列表失败！')
        }
        // console.log(res.data)
        this.OnlyTableList = res.data
      } else if (this.activeIndex === '2') {
      }
    },
    // 展示图片属性
    handlePreview(file) {
      // console.log(file)
      this.Previewpath = file.response.data.url
      this.peiviewVisible = true
    },
    // 移出图片属性
    handleRemove(file) {
      // console.log(file)
      const filePath = file.response.data.tmp_path
      const i = this.AddGoodsCate.pics.findIndex(x => x.pic === filePath)
      this.AddGoodsCate.pics.splice(i, 1)
      // console.log(this.AddGoodsCate)
    },
    // 监听上传成功的事件
    async handleSuccess(response) {
      console.log(response)
      const picInfo = { pic: response.data.tmp_path }
      this.AddGoodsCate.pics.push(picInfo)
      console.log(this.AddGoodsCate)
      // const { data: res } = await this.$http.post('upload', {
      //   tmp_path: this.picInfo,
      //   url: this.actionUrl
      // })
      // if (res.meta.status !== 200) {
      //   console.log('上传失败')
      //   return this.$message.error('上传失败')
      // }
      // console.log('上传成功')
      // this.$message.success('上传成功')
    },
    Addshop() {
      this.$refs.AddCateref.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写表要的表单项！')
        }
        // 执行添加逻辑
        const form = _.cloneDeep(this.AddGoodsCate)
        form.goods_cat = form.goods_cat.join(',')
        this.manytabledata.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join('')
          }
          this.AddGoodsCate.attrs.push(newInfo)
        })
        // 处理静态属性
        this.OnlyTableList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.AddGoodsCate.attrs.push(newInfo)
        })
        form.attrs = this.AddGoodsCate.attrs
        console.log(form)

        const { data: res } = await this.$http.post('goods', form)
        console.log(res.meta)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败！')
        }
        this.$message.success('添加成功')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId() {
      if (this.AddGoodsCate.goods_cat.length === 3) {
        return this.AddGoodsCate.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style>
.el-steps {
  /* margin-top: 20px; */
  width: 1000px;
  margin: 20px auto;
}
.priviewimg {
  width: 100%;
}
.btnAdd {
  margin-top: 20px !important;
}
</style>
